package com.lambkit.module.upms.kernel.satoken;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.config.SaCookieConfig;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.context.SaTokenContext;
import cn.dev33.satoken.util.SaTokenConsts;
import com.lambkit.auth.AuthConfig;
import com.lambkit.core.Lambkit;
import com.lambkit.core.LifecycleException;
import com.lambkit.core.plugin.Plugin;
import com.lambkit.module.upms.UpmsConfig;
import com.lambkit.plugin.satoken.SaTokenContextForLambkit;
import com.lambkit.plugin.satoken.SaTokenDaoLambkit;

/**
 * @author yangyong(孤竹行)
 */
public class SaTokenPlugin extends Plugin {
    public SaTokenPlugin(){
        AuthConfig authConfig = Lambkit.config(AuthConfig.class);
        //注册权限验证功能，由saToken处理请求上下文
        SaTokenContext saTokenContext = new SaTokenContextForLambkit();
        SaManager.setSaTokenContext(saTokenContext);
        //加载权限角色设置数据接口
        SaManager.setStpInterface(new StpInterfaceImpl());
        //设置token生成类型
        SaTokenConfig saTokenConfig = new SaTokenConfig();
        saTokenConfig.setTokenStyle(SaTokenConsts.TOKEN_STYLE_SIMPLE_UUID);
        saTokenConfig.setTimeout(authConfig.getLoginExpirationSecond());  //登录有效时间4小时
        saTokenConfig.setActiveTimeout(authConfig.getLoginExpirationSecond()); //半小时无操作过期处理
        saTokenConfig.setIsShare(false);
        saTokenConfig.setTokenName("lambkit-auth-token");    //更改satoken的cookies名称
        SaCookieConfig saCookieConfig = new SaCookieConfig();
        saCookieConfig.setHttpOnly(true);   //开启cookies 的httponly属性
        saTokenConfig.setCookie(saCookieConfig);
        SaManager.setConfig(saTokenConfig);
    }

    @Override
    public void start() throws LifecycleException {
        //增加redis缓存,需要先配置redis地址
        UpmsConfig upmsConfig = Lambkit.config(UpmsConfig.class);
        SaManager.setSaTokenDao(new SaTokenDaoLambkit("satoken", upmsConfig.getCacheType()));
    }
}
